#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py.py    
@Contact :   raogx.vip@hotmail.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2021/2/4 5:02 下午   caijiahao      1.0         Bytedancer
'''

# import lib
import sys
import logging
from logging import DEBUG, INFO, ERROR
import hashlib
import time


def create_log_id():
    m = hashlib.md5(str(time.perf_counter()).encode('utf-8'))
    return m.hexdigest()


class Logger(object):
    def __init__(self, psm, format='%(asctime)-15s %(psm)-15s %(log_id)-30s %(levelname)-4s %(filename)-5s %(message)s', level=INFO):
        # Initial construct.
        self.format = format
        self.level = level
        self.psm = psm

        # Logger configuration.
        self.console_formatter = logging.Formatter(self.format)
        self.console_logger = logging.StreamHandler(sys.stdout)
        self.console_logger.setFormatter(self.console_formatter)

        # Complete logging config.
        self.logger = logging.getLogger(self.psm)
        self.logger.setLevel(self.level)
        self.logger.addHandler(self.console_logger)
        self.extra = {
            "log_id": create_log_id(),
            "psm":self.psm
        }

    def info(self, msg, extra=None):
        if extra is not None:
            for key in extra:
                self.extra[key] = extra[key]
        self.logger.info(msg, extra=self.extra)

    def error(self, msg, extra=None):
        if extra is not None:
            for key in extra:
                self.extra[key] = extra[key]
        self.logger.error(msg, extra=self.extra)

    def debug(self, msg, extra=None):
        if extra is not None:
            for key in extra:
                self.extra[key] = extra[key]
        self.logger.debug(msg, extra=self.extra)

    def warn(self, msg, extra=None):
        if extra is not None:
            for key in extra:
                self.extra[key] = extra[key]
        self.logger.warn(msg, extra=self.extra)
